package logic

import (
	"api/model/discount"
	"api/service"
	"context"
	"github.com/zeromicro/go-zero/core/stores/sqlx"

	"api/internal/svc"
	"api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type GetBusDicountListLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewGetBusDicountListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetBusDicountListLogic {
	return &GetBusDicountListLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

// 【用户】获取折扣卡列表
func (l *GetBusDicountListLogic) GetBusDicountList(req *types.RequestBusDiscount) (resp *types.ResponseDiscountList, err error) {
	conn := sqlx.NewMysql(l.svcCtx.Config.DataSource)

	discountModel := discount.NewDiscountModel(conn)
	list, _ := discountModel.ListByBusId(l.ctx, req.BusinessId)

	resp = &types.ResponseDiscountList{
		Code: 200,
	}

	if *list == nil {
		resp.Code = 200
		return resp, nil
	}

	arr := make([]types.BusDicount, len(*list))

	var d = &types.BusDicount{
		Discount:   0,
		Money:      0,
		BusinessId: 0,
	}

	ids := make([]int64, len(*list))

	for index, item := range *list {
		d.Discount = item.Discount
		d.Money = item.Money
		d.BusinessId = item.BusinessId
		d.Sale = 0
		d.Id = item.Id

		ids[index] = item.Id

		arr[index] = *d
	}

	// 获取销量
	redis := l.svcCtx.RedisPool.Get()
	defer redis.Close()
	businessService := service.NewBusinessService(l.ctx, l.svcCtx)
	salesArr := businessService.GetDiscountSaleListByIds(redis, ids)

	if salesArr != nil {
		for index, item := range arr {
			if _, ok := salesArr[item.Id]; ok {
				arr[index].Sale = salesArr[item.Id]
			}
		}
	}

	resp.List = arr

	return resp, nil

}
